﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Buz.Service;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Common.Util.Text;
using System;
using System.Collections.Generic;
using System.Net;

namespace ST.Buz.Web.Controllers
{
	[Route("recved")]
	public class FinanceRecvController : MyBaseController
	{
		#region Ctor
		private readonly IServiceFinanceRecv service;
		private readonly IServiceFinanceRecvDetail serviceFinanceRecvDetail;
		private readonly IServiceFinanceRecvDue serviceFinanceRecvDue;
		private readonly IServicePartner servicePartner;
		private VM_RelatedModule[] relatedModules;

		public FinanceRecvController(IServiceFinanceRecv _service,
			IServiceFinanceRecvDetail _serviceFinanceRecvDetail,
			IServiceFinanceRecvDue _serviceFinanceRecvDue,
			IServicePartner _servicePartner,
			ILogger<FinanceRecvController> _logger) : base(_logger)
		{
			service = _service;
			serviceFinanceRecvDetail = _serviceFinanceRecvDetail;
			serviceFinanceRecvDue = _serviceFinanceRecvDue;
			servicePartner = _servicePartner;

			relatedModules = new VM_RelatedModule[]{
				new VM_RelatedModule(){
					id="sys_attachment",
					name="相关附件",
					count=0
				}
			};
		}
		#endregion

		#region Utilities

		private VMS_IMS_FinanceRecv GetSearchModelFromJson(JObject paras)
		{
			var vm = new VMS_IMS_FinanceRecv();
			vm.pnum = TextHelper.GetInt(paras, "pnum");
			vm.psize = TextHelper.GetInt(paras, "psize");
			vm.sortorder = TextHelper.GetString(paras, "sortorder");

			vm.sno = TextHelper.GetString(paras, "sno");
			vm.partnerid = TextHelper.GetIntNullable(paras, "partnerid");
			vm.partnername = TextHelper.GetString(paras, "partnername");
			vm.date_s = TextHelper.GetDateTimeStart(paras, "date_s");
			vm.date_e = TextHelper.GetDateTimeEnd(paras, "date_e");
			vm.state = TextHelper.GetInts(paras, "state");
			vm.ids = TextHelper.GetInts(paras, "ids");
			return vm;
		}

		private SelectListItem[] GetBuzTypeOptions()
		{
			return new SelectListItem[]{
				new SelectListItem()
				{
					Value = ((int)FinanceBuzType.加工订单).ToString(),
					Text = "加工订单"
				},
			};
		}

		private SelectListItem[] GetShareTypeOptions()
		{
			return new SelectListItem[]{
				new SelectListItem()
				{
					Value = ((int)FinanceShareType.按应收付款先后顺序).ToString(),
					Text = "按应收款先后顺序依次从总金额中扣减"
				},
				new SelectListItem()
				{
					Value = ((int)FinanceShareType.不自动分配).ToString(),
					Text = "不自动分配，按每笔应收款实际输入金额收款"
				},
			};
		}

		#endregion

		public IActionResult Index()
		{
			return RedirectToAction("List");
		}

		[ValidateSession]
		[HttpGet("list")]
		public IActionResult List()
		{
			ViewBag.ServiceCode = "845AF5E18B";

			return View();
		}

		[ValidateSession]
		[HttpGet("mlist")]
		public IActionResult MobileList()
		{
			ViewBag.ServiceCode = "845AF5E18B";

			return View();
		}

		[HttpPost("search")]
		public IActionResult Search([FromBody] JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				var searchModel = GetSearchModelFromJson(paras);
				searchModel.orgids = new int[] { sessionCurrent.OrgID };
				PageData pageData = service.GetPageList(searchModel, sessionCurrent);
				return new JsonResultPage(pageData);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpGet("add")]
		public IActionResult Add()
		{
			ViewBag.ServiceCode = "845AF5E18B";
			ViewBag.RelatedModules = relatedModules;
			ViewBag.BuzTypeOptions = GetBuzTypeOptions();
			ViewBag.ShareTypeOptions = GetShareTypeOptions();
			IMS_FinanceRecv vm = new IMS_FinanceRecv
			{
				RecvDate = DateTime.Now,
				ShareType = (int)FinanceShareType.按应收付款先后顺序,
				Details = new List<IMS_FinanceRecvDetail>()
			};
			return View("Edit", vm);
		}

		[ValidateSession]
		[HttpGet("madd")]
		public IActionResult MobileAdd()
		{
			ViewBag.ServiceCode = "845AF5E18B";
			ViewBag.RelatedModules = relatedModules;
			ViewBag.BuzTypeOptions = GetBuzTypeOptions();
			ViewBag.ShareTypeOptions = GetShareTypeOptions();
			IMS_FinanceRecv vm = new IMS_FinanceRecv()
			{
			};
			vm.RecvDate = DateTime.Now;
			vm.ShareType = (int)FinanceShareType.按应收付款先后顺序;
			vm.Details = new List<IMS_FinanceRecvDetail>();
			return View("MobileEdit", vm);
		}

		[ValidateSession]
		[HttpGet("edit/{id}")]
		[HttpGet("edit")]
		public IActionResult Edit(string id)
		{
			ViewBag.ServiceCode = "845AF5E18B";
			ViewBag.RelatedModules = relatedModules;
			ViewBag.BuzTypeOptions = GetBuzTypeOptions();
			ViewBag.ShareTypeOptions = GetShareTypeOptions();
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();

				int rowID = TextHelper.GetInt(id);
				var vm = service.GetEditDetail(rowID, sessionCurrent);
				if (vm.Details != null)
				{
					foreach (var detail in vm.Details)
					{
						if (detail.DueRecv == null)
						{
							continue;
						}
						detail.DueRecv.TotalRecved -= detail.Recved;//已付款金额减去本次付款金额
					}
				}
				return View(vm);
			}
			catch (AuthException ex)
			{
				ViewBag.ErrorMsg = ex.Message;
				return View("Error401");
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开编辑页面出错");
				ViewBag.ErrorMsg = "打开编辑页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				return View("Error500");
			}
		}

		[ValidateSession]
		[HttpGet("medit/{id}")]
		[HttpGet("medit")]
		public IActionResult MobileEdit(string id)
		{
			ViewBag.ServiceCode = "845AF5E18B";
			ViewBag.RelatedModules = relatedModules;
			ViewBag.BuzTypeOptions = GetBuzTypeOptions();
			ViewBag.ShareTypeOptions = GetShareTypeOptions();
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();

				int rowID = TextHelper.GetInt(id);
				var vm = service.GetEditDetail(rowID, sessionCurrent);
				if (vm.Details != null)
				{
					foreach (var detail in vm.Details)
					{
						if (detail.DueRecv == null)
						{
							continue;
						}
						detail.DueRecv.TotalRecved -= detail.Recved;//已付款金额减去本次付款金额
					}
				}
				return View(vm);
			}
			catch (AuthException ex)
			{
				ViewBag.ErrorMsg = ex.Message;
				return View("Error401");
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开编辑页面出错");
				ViewBag.ErrorMsg = "打开编辑页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				return View("Error500");
			}
		}

		/// <summary>
		/// 手机快捷新增收款
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[ValidateSession]
		[HttpGet("mrecv/{id}")]
		[HttpGet("mrecv")]
		public IActionResult MobileRecv(string id)
		{
			ViewBag.ServiceCode = "845AF5E18B";
			ViewBag.RelatedModules = relatedModules;
			ViewBag.BuzTypeOptions = GetBuzTypeOptions();
			ViewBag.ShareTypeOptions = GetShareTypeOptions();
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();

				int rowID = TextHelper.GetInt(id);
				var model = new VM_FinanceRecv();
				var due = serviceFinanceRecvDue.GetViewDetail(rowID, sessionCurrent);
				if (due != null)
				{
					model.DueID = due.ID;
					model.SNo = due.SNo;
					model.Stage = due.Stage;
					model.DueDate = due.DueDate;
					model.BuzType = due.BuzType;
					model.BuzID = due.BuzID;
					model.BuzSNo = due.BuzSNo;
					model.PartnerID = due.PartnerID;
					model.PartnerName = due.PartnerName;
					model.RecvStateText = due.RecvStateText;
					model.TotalRecvDue = due.TotalRecvDue;
					model.TotalRecved = due.TotalRecved;
					model.TotalRecvLeft = due.TotalRecvLeft;
					model.Comment = due.Comment;

					model.RecvDate = DateTime.Now;
					model.RecvWay = (int)FinancePayRecvWay.现金;
					model.Recv = 0;
					model.Invoice = false;

				}
				return View(model);
			}
			catch (AuthException ex)
			{
				ViewBag.ErrorMsg = ex.Message;
				return View("Error401");
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开编辑页面出错");
				ViewBag.ErrorMsg = "打开编辑页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				return View("Error500");
			}
		}

		[ValidateSession]
		[HttpGet("mrecvpartner/{id}")]
		[HttpGet("mrecvpartner")]
		public IActionResult MobileRecvPartner(string id)
		{
			ViewBag.ServiceCode = "845AF5E18B";
			ViewBag.RelatedModules = relatedModules;
			ViewBag.BuzTypeOptions = GetBuzTypeOptions();
			ViewBag.ShareTypeOptions = GetShareTypeOptions();
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();

				int rowID = TextHelper.GetInt(id);
				var model = new VM_FinanceRecvPartner
				{
					RecvDate = DateTime.Now,
					RecvWay = (int)FinancePayRecvWay.现金
				};
				var partner = servicePartner.GetViewDetail(rowID, sessionCurrent);
				if (partner != null)
				{
					model.PartnerID = partner.ID;
					model.PartnerName = partner.Name;
				}
				var statistics = serviceFinanceRecvDue.GetStatistics(rowID);
				if (statistics != null)
				{
					model.TotalRecvDue = statistics.TotalRecvDue;
					model.TotalRecved = statistics.TotalRecved;
					model.TotalRecvLeft = statistics.TotalRecvLeft;
				}
				return View(model);
			}
			catch (AuthException ex)
			{
				ViewBag.ErrorMsg = ex.Message;
				return View("Error401");
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开编辑页面出错");
				ViewBag.ErrorMsg = "打开编辑页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				return View("Error500");
			}
		}

		[ValidateSession]
		[HttpPost("save")]
		public IActionResult Save([FromBody] IMS_FinanceRecv vm)
		{
			try
			{
				CheckParams();

				if (vm.PartnerID <= 0)
				{
					throw new BuzException("请选择客户或供应商");
				}
				if (vm.TotalRecv <= 0)
				{
					throw new BuzException("收款金额有误");
				}
				switch (vm.ShareType)
				{
					case (int)FinanceShareType.不自动分配:
					case (int)FinanceShareType.平均分配总金额:
					case (int)FinanceShareType.按应收付款先后顺序:
					case (int)FinanceShareType.按应收付款比例:
						break;
					default:
						throw new BuzException("请选择收款方式");
				}
				//if (vm.Details == null || vm.Details.Count == 0)
				//{
				//	throw new BuzException("收款明细不能为空");
				//}
				//if (!string.IsNullOrEmpty(vm.Detail.Detail))//去除换行等字符
				//{
				//	string strDetail = vm.Detail.Detail;
				//	vm.Detail.Detail = strDetail.Replace("\r", "").Replace("\n", "");
				//}
				UserSession sessionCurrent = GetSessionFromRequest();

				int rowID = service.AddOrUpdate(vm, sessionCurrent);

				return new JsonResultBase(rowID);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "新增失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("savequick")]
		public IActionResult SaveQuick([FromBody] VM_FinanceRecv vm)
		{
			try
			{
				CheckParams();

				if (vm.DueID <= 0)
				{
					throw new BuzException("请选择应收款");
				}
				UserSession sessionCurrent = GetSessionFromRequest();
				var due = serviceFinanceRecvDue.GetViewDetail(vm.DueID, sessionCurrent);
				if (due == null)
				{
					throw new BuzException("应收款无效");
				}
				var details = new List<IMS_FinanceRecvDetail> {
					new IMS_FinanceRecvDetail{
					DueID = due.ID,
					DueSNo = due.SNo,
					Recved = vm.Recv,
					DetailAddDate = DateTime.Now,
					OrgID = sessionCurrent.OrgID,
					DueRecv = due
					}
				};
				var recv = new IMS_FinanceRecv()
				{
					ShareType = (int)FinanceShareType.按应收付款先后顺序,
					PartnerID = due.PartnerID,
					PartnerName = due.PartnerName,
					RecvDate = vm.RecvDate,
					RecvWay = vm.RecvWay,
					BillNo = vm.BillNo,
					Invoice = vm.Invoice,
					InvoiceNo = vm.InvoiceNo,
					TotalRecv = vm.Recv,
					StateNow = 0,
					Comment = vm.Remark,
					AddDate = DateTime.Now,
					AddManID = sessionCurrent.UserID,
					AddManName = sessionCurrent.UserName,
					OrgID = sessionCurrent.OrgID,
					Details = details
				};
				int rowID = service.AddOrUpdate(recv, sessionCurrent);

				return new JsonResultBase(rowID);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "新增失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("savepartnerquick")]
		public IActionResult SavePartnerQuick([FromBody] VM_FinanceRecvPartner vm)
		{
			try
			{
				CheckParams();

				if (vm.PartnerID == 0)
				{
					throw new BuzException("布行ID不能为空");
				}
				decimal recvLeft = vm.Recv;
				if (recvLeft <= 0)
				{
					throw new BuzException("本次收款金额不能为空");
				}
				UserSession sessionCurrent = GetSessionFromRequest();
				var details = new List<IMS_FinanceRecvDetail>();
				var dues = serviceFinanceRecvDue.GetList(new VMS_IMS_FinanceRecvDue { partnerid = vm.PartnerID, state = new int[] { (int)FinancePayRecvState.未收, (int)FinancePayRecvState.部分已收 }, buztype = (int)FinanceBuzType.加工订单, pnum = 1, psize = 100 }, sessionCurrent);
				foreach (var due in dues)
				{
					if (recvLeft <= 0)
					{
						continue;
					}
					// 当前应收款收款金额
					decimal current = due.TotalRecvLeft > recvLeft ? recvLeft : due.TotalRecvLeft;

					details.Add(new IMS_FinanceRecvDetail
					{
						DueID = due.ID,
						DueSNo = due.SNo,
						Recved = current,
						DetailAddDate = DateTime.Now,
						OrgID = sessionCurrent.OrgID,
						DueRecv = due
					});
					recvLeft -= current;
				}
				var recv = new IMS_FinanceRecv()
				{
					ShareType = (int)FinanceShareType.按应收付款先后顺序,
					PartnerID = vm.PartnerID,
					PartnerName = vm.PartnerName,
					RecvDate = vm.RecvDate,
					RecvWay = vm.RecvWay,
					BillNo = vm.BillNo,
					Invoice = vm.Invoice,
					InvoiceNo = vm.InvoiceNo,
					TotalRecv = vm.Recv,
					StateNow = 0,
					Comment = vm.Remark,
					AddDate = DateTime.Now,
					AddManID = sessionCurrent.UserID,
					AddManName = sessionCurrent.UserName,
					OrgID = sessionCurrent.OrgID,
					Details = details
				};
				int rowID = service.AddOrUpdate(recv, sessionCurrent);

				return new JsonResultBase(true);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "新增失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpGet("view/{id}")]
		[HttpGet("view")]
		public IActionResult ViewDetail(string id)
		{
			ViewBag.ServiceCode = "845AF5E18B";
			ViewBag.RelatedModules = relatedModules;
			ViewBag.BuzTypeOptions = GetBuzTypeOptions();
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				int rowID = TextHelper.GetInt(id);
				var vm = service.GetViewDetail(rowID, sessionCurrent);
				if (vm.Details != null)
				{
					vm.DetailRecvAmountTotal = 0;
					foreach (var detail in vm.Details)
					{
						vm.DetailRecvAmountTotal += detail.Recved;
					}
				}
				return View("View", vm);
			}
			catch (AuthException ex)
			{
				ViewBag.ErrorMsg = ex.Message;
				return View("Error401");
			}
			catch (EntityNotFoundException ex)
			{
				logger.LogError(ex, "打开查看页面出错");
				ViewBag.ErrorMsg = "未找到相关记录或记录已删除，详细错误信息如下：" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				return View("Error404");
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开查看页面出错");
				ViewBag.ErrorMsg = "打开查看页面失败，详细错误信息如下：" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				return View("Error500");
			}
		}

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpGet("mview/{id}")]
		[HttpGet("mview")]
		public IActionResult MobileViewDetail(string id)
		{
			ViewBag.ServiceCode = "845AF5E18B";
			ViewBag.RelatedModules = relatedModules;
			ViewBag.BuzTypeOptions = GetBuzTypeOptions();
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				int rowID = TextHelper.GetInt(id);
				var vm = service.GetViewDetail(rowID, sessionCurrent);
				if (vm.Details != null)
				{
					vm.DetailRecvAmountTotal = 0;
					foreach (var detail in vm.Details)
					{
						vm.DetailRecvAmountTotal += detail.Recved;
					}
				}
				return View("MobileView", vm);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpPost("detail")]
		public IActionResult ViewJson([FromBody] JObject paras)
		{
			try
			{
				CheckParams();

				int id = TextHelper.GetInt(paras, "id");

				var model = service.Get(id);

				if (model == null)
				{
					return new JsonResultBase(false, "未找到相关记录", (int)HttpStatusCode.NotFound);
				}

				return new JsonResultBase(model);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("delete")]
		public IActionResult Delete([FromBody] JObject paras)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();
				var rowID = TextHelper.GetInt(paras, "id");
				var result = service.Delete(rowID, sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("batchdelete")]
		public IActionResult BatchDelete([FromBody] int[] ids)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();

				var result = service.BatchDelete(ids, sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 相关记录查询
		/// </summary>
		/// <param name="paras"></param>
		/// <returns></returns>
		[HttpPost("relatedbydue")]
		public IActionResult RelatedByDue([FromBody] JObject paras, UserSession _session)
		{
			var searchModel = GetSearchModelFromJson(paras);
			searchModel.dueid = TextHelper.GetInt(paras, "infoid");
			if (!searchModel.dueid.HasValue || searchModel.dueid.Value <= 0)
			{
				throw new ArgumentNullException("相关记录ID");
			}
			var pageData = service.GetPageList(searchModel, _session);
			return new JsonResultPage(pageData);
		}

		[HttpPost("countbydue")]
		public IActionResult CountByDue([FromBody] JObject paras, UserSession _session)
		{
			var searchModel = GetSearchModelFromJson(paras);
			searchModel.dueid = TextHelper.GetInt(paras, "infoid");
			if (!searchModel.dueid.HasValue || searchModel.dueid.Value <= 0)
			{
				throw new ArgumentNullException("相关记录ID");
			}
			var result = service.GetCount(searchModel, _session);
			return new JsonResultBase(result);
		}

		[HttpPost("export")]
		public IActionResult Export(JObject obj)
		{
			//context.Response.ContentType = "application/vnd.ms-excel";
			//context.Response.Charset = "UTF-8";
			//context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
			//context.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}_{1}.xls", HttpUtility.UrlEncode(Title), DateTime.Now.ToString("yyyyMMdd_HHmmss")));
			//switch (context.Request.QueryString["all"])
			//return File(byte)
			throw new NotImplementedException();
		}

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpGet("scan/{id}")]
		[HttpGet("scan")]
		public IActionResult Scan(string id)
		{
			ViewBag.ServiceCode = "845AF5E18B";
			int rowID = TextHelper.GetInt(id);
			var vm = new { };
			return View(vm);
		}
	}
}
